from docx import Document
import os


def split_docx(file_path, max_size=5 * 1024 * 1024):
    # 打开文档
    doc = Document(file_path)

    # 获取所有段落
    paragraphs = doc.paragraphs

    # 创建目录存放切分后的文档
    output_dir = "split_docs"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 初始化切分后的文档
    doc_parts = []
    current_doc = Document()
    current_size = 0

    # 按照段落逐个添加，直到文件大小超过限制
    for para in paragraphs:
        # 将段落添加到当前文档
        current_doc.add_paragraph(para.text)

        # 临时保存当前文档并检查大小
        temp_path = "temp.docx"
        current_doc.save(temp_path)
        current_size = os.path.getsize(temp_path)

        if current_size > max_size:
            # 文件超过最大大小，保存并创建新文档
            new_file_name = os.path.join(output_dir, f"part_{len(doc_parts) + 1}.docx")
            current_doc.save(new_file_name)
            doc_parts.append(new_file_name)
            # 创建新文档继续添加
            current_doc = Document()
            current_doc.add_paragraph(para.text)

    # 最后一个文档保存
    if current_size <= max_size and len(current_doc.paragraphs) > 0:
        new_file_name = os.path.join(output_dir, f"part_{len(doc_parts) + 1}.docx")
        current_doc.save(new_file_name)
        doc_parts.append(new_file_name)

    # 删除临时文件
    os.remove(temp_path)

    return doc_parts


# 调用示例
file_path = "stem cells in veterinary science (ratan kumar choudhary, shanti choudhary) (z-library).docx"  # 输入文件路径
split_docx(file_path)
